<template>
  <div class="app-container">
    <el-card class="filter-container" :style="{ marginBottom: '20px' }" :shadow="defaultData.cardShadow">
      <div class="operate-container">
        <div>
          <i class="el-icon-search"></i>
          <span>筛选搜索</span>
        </div>
        <div>
          <el-button style="float: right" type="primary" @click="getList()">
            搜索
          </el-button>
          <el-button style="float: right; margin-right: 15px" @click="handleResetSearch()">
            重置
          </el-button>
        </div>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="powerfulTableData.listQuery">
          <div class="screenForm">
            <el-form-item label="合作方名称：" prop="partnerName">
              <el-input v-model="powerfulTableData.listQuery.partnerName" placeholder="请输入合作方名称" clearable />
            </el-form-item>
            <el-form-item label="手机号：" prop="mobileNumber">
              <el-input v-model="powerfulTableData.listQuery.mobileNumber" placeholder="请输入手机号" clearable />
            </el-form-item>
          </div>
        </el-form>

      </div>
    </el-card>

    <el-card :shadow="defaultData.cardShadow">
      <div class="operate-container">
        <div>
          <i class="el-icon-tickets"></i>
          <span>数据列表</span>
        </div>

        <div class="flex">
          <el-button type="success" class="btn-add" @click="handleAdd()">
            新增
          </el-button>
          <el-button type="primary" @click="importDialogVisible = true">导入</el-button>
          <el-button type="primary" plain class="btn-add" @click="handleDownloadTemplate">
            下载模版
          </el-button>
        </div>
      </div>

      <div>
        <PowerfulTable :list="powerfulTableData.list" :header="header" :isSelect="false" :property="property"
          :pagination-property="{
            total: powerfulTableData.total,
            pageSizes: [2, 5, 7],
          }" @size-change="getList" @component-event="handleComponentChange" @btn-click="handleBtnClick">
          <template #createTime="{ row }">
            <div>{{ formatTime(row.createTime) }}</div>
          </template>
          <template #updateTime="{ row }">
            <div>{{ formatTime(row.updateTime) }}</div>
          </template>
          <template #accountState="{ row }">
            <div>{{ row.accountState == 0 ? '停用' : '正常' }}</div>
          </template>
          <template #partnerType="{ row }">
            <div>{{ partnerTypeMap.get(row.partnerType) }}</div>
          </template>
        </PowerfulTable>
        <el-pagination v-model:current-page="powerfulTableData.listQuery.pageNum" class="pagination-container"
          v-model:page-size="powerfulTableData.listQuery.pageSize" :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next" :total="powerfulTableData.total" @size-change="sizeChange"
          @current-change="getList" />
      </div>
    </el-card>

    <!-- 编辑区 -->
    <Update v-model:dialog="isDialog" v-if="isDialog" v-model:currentForm="currentForm" @refresh="getList" />

    <!-- 导入确认对话框 -->
    <el-dialog v-model="importDialogVisible" title="导入确认" width="500px">
      <div style="margin-bottom: 20px;">
        <el-form-item label="地区" prop="cityCode">
          <area-code v-model:provinceCode="formData.provinceCode" v-model:cityCode="formData.cityCode"
            :showArea="false" />
        </el-form-item>
      </div>

      <template #footer>
        <span class="dialog-footer flex">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <Upload
            :action="`/admin-core/web/partner/v1/import?provinceCode=${formData.provinceCode}&cityCode=${formData.cityCode}`"
            @success="handleImportSuccess" />
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { partnerQuery, removePartnerAccount, getPartnerTemplate } from '@/api/user'
import { useData, Model } from './indexData'
import { Handlers } from 'el-plus-powerful-table'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores'
import Update from './update.vue'
import Upload from '@/components/upload/index.vue'
import { formatTime, downloadFile } from '@/utils'
import { partnerTypeMap, property } from '@/config/constants'
const { header, powerfulTableData, currentForm, isDialog } = useData()
import AreaCode from '@/components/area-code/index.vue'
// 导入对话框显示状态
const importDialogVisible = ref(false)
import { defaultData as defaultForm } from './indexData'
const userStore = useUserStore()

// 导入表单数据
const formData = reactive({
  provinceCode: '',
  cityCode: '',
})



// 获取用户列表
const getList = () => {
  partnerQuery(powerfulTableData.listQuery).then((res) => {
    console.log(res)
    powerfulTableData.list = res.data.list
    powerfulTableData.total = res.data.total
  })
}
// 分页大小改变
const sizeChange = (val: number) => {
  powerfulTableData.listQuery.pageSize = val
  getList()
}
getList()

const handleComponentChange: Handlers['component-event'] = (payload) => {
  switch (payload.componentName) {
    // 停用事件
    case 'switch':
      const e = payload.row
      if (userStore.userInfo.id == e.id && e.status === 0) {
        ElMessage.error('你的账号已被停用！')
      }
      break
  }
}

const handleAdd = () => {
  Object.assign(currentForm.value, defaultForm())
  isDialog.value = true;
}

const handleDownloadTemplate = () => {
  getPartnerTemplate().then((res: any) => {
    downloadFile(res, '合作方及账号信息导入模版.xlsx')
  })
}

// 处理导入成功
const handleImportSuccess = () => {
  // 关闭对话框
  importDialogVisible.value = false
  // 刷新列表
  getList()
}

const handleBtnClick: Handlers['btn-click'] = ({ params, row }) => {
  console.log(row)
  switch (params) {
    case 'edit':
      isDialog.value = true;
      Object.assign(currentForm.value, JSON.parse(JSON.stringify(row)))
      break
    case 'remove':
      remove(row)
      break
  }
}

const remove = (row: Model) => {
  ElMessageBox.confirm('是否确认删除', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    removePartnerAccount({ partnerUuid: row.partnerUuid }).then(() => {
      ElMessage.success('删除成功！')
      getList()
    })
  })
}

// 分配菜单
const handleAddRole = () => {
  // switchs.role = false
  // powerfulTableData.list = powerfulTableData.list.map((item: RowType) => {
  //   if (item.id == (currentForm.value as RowType).id) {
  //     item = currentForm.value as RowType
  //   }
  //   return item
  // })
}

// 重置
const handleResetSearch = () => {
  Object.keys(powerfulTableData.listQuery).forEach((item: any) => {
    let arr = ['pageNum', 'pageSize']
    if (arr.indexOf(item) == -1) {
      ; (powerfulTableData.listQuery as { [s: string]: string | number })[item] =
        ''
    }
  })
  getList()
}
</script>
